package com.xxl.sso.server.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.xxl.sso.server.core.model.UserInfo;
import com.xxl.sso.server.core.result.ReturnT;

import com.xxl.sso.server.mapper.UserMapper;
import com.xxl.sso.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private static List<UserInfo> mockUserList = new ArrayList<>();
    static {
        for (int i = 0; i <5; i++) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(1000+i);
            userInfo.setUsername("user" + (i>0?String.valueOf(i):""));
            userInfo.setPassword("123456");
            mockUserList.add(userInfo);
        }
    }

    @Override
    public ReturnT<UserInfo> findUser(String username, String password) {

        if (username==null || username.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "请输入用户名.");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "请输入密码.");
        }

         //mock user (改造它成为从数据库取密码进行验证)
         for (UserInfo mockUser: mockUserList) {
             if (mockUser.getUsername().equals(username) && mockUser.getPassword().equals(password)) {
                 return new ReturnT<UserInfo>(mockUser);
             }
         }
        //根据用户名查询是否有此用户
//        UserInfo user = new UserInfo();
//        user.setUsername(username);
//        //校验用户名
//        UserInfo userInfo = userMapper.selectOne(user);
//        //如果存在
//        if(null != userInfo){
//            //将用户输入的密码进行md5加密后再与数据库进行比较
//            if (SecureUtil.md5(password).equals(userInfo.getPassword())) {
//                return new ReturnT<UserInfo>(userInfo);
//            }
//        }
//
        return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "用户名或密码无效.");
    }


}
